package org.example.attendancesystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.attendancesystem.domain.*;
import org.example.attendancesystem.service.*;
import org.example.attendancesystem.service.impl.AttendanceRecordsServiceImpl;
import org.example.attendancesystem.service.impl.StudentsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/attendance")
public class AttendaceController {
    @Autowired
    AttendanceSessionsService attendanceSessionsService;
    @Autowired
    SessionParamsService sessionParamsService;
    @Autowired
    ClassesService classesService;
    @Autowired
    StudentsService studentsService;
    @Autowired
    AttendanceRecordsService attendanceRecordsService;

    @GetMapping("/list")
    public Result<IPage<AttendanceSessions>> getAll(
            @RequestParam int currentPage,  // 修正参数名（前端传的是currentPage）
            @RequestParam int pageSize,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String sessionType) {

        // 1. 创建分页对象（使用前端传入的分页参数）
        Page<AttendanceSessions> page = new Page<>(currentPage, pageSize);

        // 2. 构建查询条件
        QueryWrapper<AttendanceSessions> wrapper = new QueryWrapper<>();

        // 标题模糊查询
        if (StringUtils.isNotBlank(title)) {
            wrapper.like("title", title);
        }

        // 签到类型精确匹配
        if (StringUtils.isNotBlank(sessionType)) {
            wrapper.eq("session_type", sessionType);
        }

        // 3. 执行分页查询（带上查询条件）
        IPage<AttendanceSessions> attendanceSessionsPage = attendanceSessionsService.page(page, wrapper);

        // 4. 转换班级ID为班级名称
        List<AttendanceSessions> records = attendanceSessionsPage.getRecords();
        for (AttendanceSessions session : records) {
            Classes classInfo = classesService.getById(session.getClassId());
            if (classInfo != null) {
                session.setClassId(classInfo.getClassName()); // 注意：这里实际是设置班级名称到classId字段
            }
        }

        // 5. 返回分页结果
        return Result.success(attendanceSessionsPage);
    }

    @PostMapping("/add")
    public Result<String> add(@RequestBody AttendanceSessions attendanceSessions) {
        System.out.println(attendanceSessions);
        // 调用服务层添加方法
        if(attendanceSessions.getSessionType().equals("普通")){
            SessionParams sessionParams = new SessionParams();
            sessionParams.setSessionType(attendanceSessions.getSessionType());
            boolean yes = sessionParamsService.save(sessionParams);
        }
        boolean isSuccess = attendanceSessionsService.save(attendanceSessions);

//        //添加学生签到记录为未签到
        QueryWrapper<Students> wrapper1 = new QueryWrapper<Students>()
                .eq("class_id",attendanceSessions.getClassId());
        List<Students> studentsList = studentsService.list(wrapper1);
        for (Students students : studentsList) {
            AttendanceRecords attendanceRecords = new AttendanceRecords();
            attendanceRecords.setStudentId(students.getStudentId());
            attendanceRecords.setSessionId(attendanceSessions.getSessionId());
            attendanceRecords.setSessionType((String) attendanceSessions.getSessionType());
            attendanceRecords.setStatus("未签到");

            attendanceRecordsService.save(attendanceRecords);
        }



        if (isSuccess) {
            return Result.success("添加成功");
        } else {
            return Result.fail("添加失败");
        }
    }
    @PutMapping("/update/{sessionId}")
    public Result<String> update(@PathVariable("sessionId") Long sessionId, @RequestBody AttendanceSessions attendanceSessions) {
        attendanceSessions.setSessionId(sessionId);
        Classes classes = classesService.query().eq("class_name", attendanceSessions.getClassId()).one();
        attendanceSessions.setClassId(classes.getClassId());
        System.out.println(attendanceSessions);
        // 调用服务层更新方法
        boolean isSuccess = attendanceSessionsService.updateById(attendanceSessions);
        if (isSuccess) {
            return Result.success("更新成功");
        } else {
            return Result.fail("更新失败");
        }
    }
    @DeleteMapping("/delete/{sessionId}")
    public Result<String> delete(@PathVariable("sessionId") Long sessionId) {
        // 调用服务层删除方法
        boolean yes = sessionParamsService.removeById(sessionId);
        boolean isSuccess = attendanceSessionsService.removeById(sessionId);
        if (isSuccess) {
            return Result.success("删除成功");
        } else {
            return Result.fail("删除失败");
        }
    }
    @GetMapping("/listResult")
    public Result<IPage<AttendanceDetail>> getAllResult(
            @RequestParam int currentPage,
            @RequestParam int pageSize,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String sessionType) {

        // 1. 创建分页对象（使用前端传入的分页参数）
        Page<AttendanceSessions> page = new Page<>(currentPage, pageSize);

        // 2. 构建查询条件
        QueryWrapper<AttendanceSessions> wrapper = new QueryWrapper<>();

        // 标题模糊查询
        if (StringUtils.isNotBlank(title)) {
            wrapper.like("title", title);
        }

        // 签到类型精确匹配
        if (StringUtils.isNotBlank(sessionType)) {
            wrapper.eq("session_type", sessionType);
        }

        // 3. 执行分页查询（带上查询条件）
        IPage<AttendanceSessions> sessionsPage = attendanceSessionsService.page(page, wrapper);

//        System.out.println(sessionsPage.getRecords());
        // 4. 转换为AttendanceDetail分页对象
        IPage<AttendanceDetail> attendanceDetailPage = sessionsPage.convert(session -> {
            AttendanceDetail detail = new AttendanceDetail();

            // 基础信息
            detail.setSessionId(session.getSessionId());
            detail.setTitle(session.getTitle());
            detail.setSessionType(session.getSessionType());
            detail.setLateRange(session.getLateRange());

            // 班级信息
            Classes classes = classesService.getById(session.getClassId());
            if (classes != null) {
                detail.setClassId(classes.getClassName());
            }

            // 统计学生人数
            QueryWrapper<Students> studentWrapper = new QueryWrapper<>();
            studentWrapper.eq("class_id", session.getClassId());
            detail.setNumber((int) studentsService.count(studentWrapper));

            return detail;
        });
//        System.out.println(attendanceDetailPage.getRecords());
        // 5. 返回分页结果
        return Result.success(attendanceDetailPage);
    }
    @GetMapping("/latestQRCodeSession")
    public Result getLatestQRCodeSession() {
        // 查询 session_type 为 "二维码" 的最新签到会话
        QueryWrapper<AttendanceSessions> wrapper = new QueryWrapper<>();
        wrapper.eq("session_type", "二维码");  // 根据 session_type 过滤为 "二维码"
        wrapper.orderByDesc("created_at");     // 按照创建时间降序排列，获取最新的会话
        wrapper.last("LIMIT 1");               // 强制限制只返回一条记录

        // 执行查询，获取最新的二维码签到会话
        AttendanceSessions latestSession = attendanceSessionsService.getOne(wrapper);

        // 判断是否找到二维码会话，返回会话的所有信息
        if (latestSession != null) {
            return Result.success(latestSession);  // 返回最新的会话对象
        } else {
            return Result.fail("未找到二维码会话");
        }
    }








}
